<script setup lang="ts">
import { ref, watch } from "vue";
import { onLoad, onPageScroll, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { useInfiniteScroll } from "@/composables/useInfiniteScroll";
import { getListByUser, removeNeed } from "@/api/needs";
import { handleToPage } from "@/utils";

const { items: list, isLoading, hasMore, error, resetAndLoad, loadMore } = useInfiniteScroll(getListByUser);

const tabs = [
  { key: '', label: '全部需求'},
  { key: '0', label: '待审核'},
  { key: '1', label: '已通过'},
  { key: '2', label: '已拒绝'}
];
/** 查询参数  */
const queryParams = ref({
  status: ''
});

watch(queryParams, (newQueryParams) => {
  console.log("Query Params changed:", newQueryParams);
  resetAndLoad(newQueryParams);
}, { deep: true });

// 页面加载
onLoad(() => {
  resetAndLoad(queryParams.value);
});

// 监听用户下拉动作
onPullDownRefresh(() => {
  resetAndLoad(queryParams.value).finally(() => {
    // 停止当前页面下拉刷新
    uni.stopPullDownRefresh();
  });
});

// 页面滚动到底部的事件
onReachBottom(() => loadMore());

/** 取消活动 */
function handleApplyCancel(id: number){
  uni.showModal({
		  title:'提示',
			content:'是否确认删除 ?',
			success: async({confirm}) => {
				if(confirm) {
          await removeNeed({id});
          // 取消成功，手动删除列表项
          const idx = list.value.findIndex(item=>item.id==id);
          list.value.splice(idx,1);
          uni.showToast({ title: '删除成功', icon:'none' });
        }
			}
	})
}

const popupVisible = ref(false);
const actionId = ref(0);
function handleOpenPopup(id:number) {
  actionId.value = id;
  popupVisible.value = true;
}

async function handleDelete() {
  await removeNeed({id: actionId.value});
  // 取消成功，手动删除列表项
  const idx = list.value.findIndex(item=>item.id==actionId.value);
  list.value.splice(idx,1);
  popupVisible.value = false;
  uni.showToast({ title: '删除成功', icon:'none' });
}

// 吸顶变色
const isScrolled = ref(false);
onPageScroll((e)=>{
  isScrolled.value = e.scrollTop > 0;
});
</script>
<template>
<view class="relative overflow-hidden">
  <page-navbar title="我的需求" :hideTitle="true" :isScrolled="isScrolled"></page-navbar>
  
  <page-title title="我的需求"></page-title>

  <view class="my-1 overflow-x-auto scrollbar-hide">
    <view class="w-fit flex gap-2 p-4">
      <view
        class="rounded-full px-3 py-1 box-border break-keep text-sm"
        :class="[queryParams.status == item.key ? 'text-white bg-gradient-to-r from-#5199F9 to-#0164E6' : 'text-black/80 bg-white border-(~ solid black/8)']"
        v-for="(item, index) in tabs" :key="index"
        @click="queryParams.status = item.key"
      >
        {{ item.label }}
      </view>
    </view>
  </view>

  <page-list :list="list" :hasMore="hasMore" :isLoading="isLoading" :loadMore="loadMore">
    <view
      class="relative mx-4 mb-3 p-3 rounded-lg grid grid-cols-[auto_1fr] gap-2 border-(~ solid black/4) bg-(gradient-to-b no-repeat) to-black/0"
      :class="{
        'from-#1373FF/12':item.status == 0, 
        'from-#00C777/8':item.status == 1, 
        'from-#EA0000/4':item.status == 2
      }"
      v-for="item in list" :key="item.id"
    >
      <image v-if="item.status == 0" class="w-14 h-9 absolute -top-1 -right-0.5 z-1" src="https://static.minglvtang.com/images/icons/state_warn.png" mode="widthFix" />
      <image v-if="item.status == 1" class="w-14 h-9 absolute -top-1 -right-0.5 z-1" src="https://static.minglvtang.com/images/icons/state_success.png" mode="widthFix" />
      <image v-if="item.status == 2" class="w-14 h-9 absolute -top-1 -right-0.5 z-1" src="https://static.minglvtang.com/images/icons/state_error.png" mode="widthFix" />
      <view class="text-(xs #666666) pb-3 border-b-(~ solid #E5E5E5) col-span-2">需求编号：{{item.id}}</view>
      <image class="size-14" src="https://static.minglvtang.com/images/icons/needs_warn.png" mode="aspectFill" />
      <view class="grid items-center" @click="handleToPage(`/pages/need/detail?id=${item.id}`)">
        <view class="flex items-center">
          <view class="text-(sm #333333) line-clamp-1">{{item.title}}</view>
          <view class="i-ri-arrow-right-s-line"></view>
        </view>
        <view class="text-(sm #666666) line-clamp-1">{{item.desc}}</view>
      </view>
      <view class="col-span-2 pt-3 flex gap-3 items-center justify-end border-t-(~ solid #E5E5E5)">
        <view 
          v-if="item.status!=1"
          class="text-(sm #333333) rounded-full border-(~ solid #D8D8D8) px-3 py-1 flex items-center justify-around"
          @click="handleToPage(`/pages/need/post?id=${item.id}`)"
        >
          <view class="i-mdi-light-pencil"></view>编辑
        </view>
        <view 
          class="text-(sm #333333) rounded-full border-(~ solid #D8D8D8) px-3 py-1 flex items-center justify-around"
          @click="handleOpenPopup(item.id)"
        >
          <view class="i-mdi-light-delete"></view>删除
        </view>
      </view>
    </view>
  </page-list>

  <view class="fixed inset-0 z-50 bg-black/60 w-screen h-screen" v-show="popupVisible">
    <view class="absolute left-50% -translate-x-50% w-86 rounded-b-2xl bottom-3 mb-[--safe-area-inset-bottom] page-popup">
      <view class="text-(lg #333333) px-5">删除需求</view>
      <view class="px-5 pb-5 mt-2 bg-gradient-to-b from-white/0 from-10% to-white">
        <view class="text-(2xl #333333)">是否确认删除这条需求？删除后无法恢复</view>
        <view class="mt-10 flex space-x-4">
          <view class="flex-1">
            <uv-button
              type="primary"
              size="large"
              text="确认删除"
              :custom-style="{
                fontSize: '18px',
                backgroundImage: 'linear-gradient(to right, #5199F9, #0164E6)',
                height: '48px',
                borderRadius: '8px',
                borderColor: 'transparent'
              }"
              @click="handleDelete"
            ></uv-button>
          </view>
          <view class="flex-1">
            <uv-button
              size="large"
              text="取消"
              :custom-style="{
                fontSize: '18px',
                height: '48px',
                borderRadius: '8px',
                borderColor: '#D8D8D8'
              }"
              @click="popupVisible = false"
            ></uv-button>
          </view>
        </view>
      </view>
    </view>
  </view>
  
</view>
</template>
